package com.liuzhilin.controller;

import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
/*
* 用户注册
* */
@WebServlet("/userRegister")
public class UserRegister extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        // 设置响应头，允许跨域请求
        Response.setCorsHeaders(response);
        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        BufferedReader reader = request.getReader();
        // 读取请求体数据
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject requestJson = new JSONObject(sb.toString());

        String username = requestJson.getString("username");
        String password = requestJson.getString("password");
        String personalSignature = requestJson.getString("personalSignature");
        String birthday = requestJson.getString("birthday");
        //前端实现了
       /* // 验证密码是否一致
        if (!password.equals(confirmPassword)) {
            out.print("{\"message\": \"两次输入的密码不一致！\"}");
            response.setStatus(400);
            return;
        }*/
        // 调用业务逻辑层进行注册,判断注册是否合理
        String result = UserService.userRegister(username, password, personalSignature, birthday);
        if (result.equals("注册成功！")) {
            out.print("{\"message\": \"注册成功！\"}");
            response.setStatus(200);
        }else{
            out.print("{\"message\": \""+result+"\"}");
            response.setStatus(400);
        }

    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response){
        Response.setCorsHeaders(response);
    }
}
